package ui;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * @author xiaguojin
 * @time 2020-05-20 10:03
 * @change
 * @chang time
 * @class 自定义view 画布练习
 */
public class TrackView extends View {

    private Path mPath = new Path();

    //贝瑟尔曲线的起始点
    float startX,startY;

    public TrackView(Context context) {
        super(context);
    }

    public TrackView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                mPath.moveTo(event.getX(), event.getY());
                startX = event.getX();
                startY = event.getY();
                return true;
            }
            case MotionEvent.ACTION_MOVE:
                mPath.lineTo(event.getX(), event.getY());
                float endX = (startX + event.getX())/2;
                float endY = (startY +event.getY())/2;
                mPath.quadTo(startX,startY,endX,endY);
                startX = event.getX();
                startY = event.getY();
                invalidate();
                break;
            default:
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(2);

        canvas.drawPath(mPath, paint);
    }

    public void reset() {
        mPath.reset();
        invalidate();
    }

}
